<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column
            label="头像"
            sortable=""
            align="center"
          >
            <!-- @click="" -->
            <template v-slot="{row}">
              <img
                slot="reference"
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column
            label="入职时间"
            sortable=""
            prop="timeOfEntry"
            :formatter="formatterTime"
          />
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('point-user-delete')"
                @click="deleteEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 弹窗组件 -->
    <add-employee
      :show-dialog.sync="showDialog"
      @addEmployee="getEmployeeList"
    />
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 角色弹框 -->
    <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>
<script>
import moment from 'moment' // 全局注册moment
import QrCode from 'qrcode'
import addEmployee from './components/add-employee.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AssignRole from '@/views/employees/components/assign-role.vue'
// 组件实例的构造参数，基于这个对象取构造组件
export default {
  components: { addEmployee, AssignRole },
  data() {
    return {
      loading: false,
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0 // 总数
      },
      showDialog: false, // 控制弹层的显示
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 分页功能
    changePage(newPage) {
      this.page.page = newPage // 跟新到最新页码
      this.getEmployeeList()
    },
    // 获取初始数据
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    // 格式化聘用形式 （表格列的属性：formatter）
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 格式化时间
    formatterTime(row, column, cellValue, index) {
      return moment(cellValue).format('YYYY-MM-DD')
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id) // 删除请求
        this.$message.success('删除员工成功')
        this.getEmployeeList() // 重新拉取数据跟新页面
        // if (this.page.total%this.page.size===0) {
        //  this.page.page=1
        // }
      } catch (error) {
        console.log(error)
      }
    },
    // 处理导出数据方法
    translate(inputData = [], mapRelation = {}) {
      const header = Object.keys(mapRelation)// 拿到所有属性名
      return inputData.map((item) => {
        const arr = []
        header.forEach((zhKey) => {
          const enKey = mapRelation[zhKey]// 拿到对应属性名的属性值
          const value = item[enKey]// 处理数据中对应的值
          // // 处理时间
          // if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          //   value = value ? moment(value).format('YYYY-MM-DD') : moment(new Date()).format('YYYY-MM-DD')
          // }
          // // 处理聘用形式
          // if (enKey === 'formOfEmployment') {
          //   const obj = EmployeeEnum.hireType.find((item) => item.id === value)
          //   value = obj ? obj.value : '未知'
          // }
          arr.push(value)
        })
        return arr
      })
    },
    // 导出数据方法 在点击导出时触发
    exportData() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并表格（:表示范围）
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取渲染页面的全部数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // rows.map(item => {
        //   // 处理时间
        //   if (item['入职日期'] === 'timeOfEntry' || item['聘用形式'] === 'correctionTime') {
        //     value = value ? moment(value).format('YYYY-MM-DD') : moment(new Date()).format('YYYY-MM-DD')
        //   }
        //   // 处理聘用形式
        //   if (item['聘用形式'] === 'formOfEmployment') {
        //     const obj = EmployeeEnum.hireType.find((item) => item.id === value)
        //     value = obj ? obj.value : '未知'
        //   }
        // })
        const data = this.translate(rows, headers)
        const header = Object.keys(headers)
        excel.export_json_to_excel({
          filename: '人力资源表格',
          data,
          header,
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },
    // 转换二维码
    showQrCode(url) {
      // url不存在，不显示弹框
      if (!url) return this.$message.warning('该用户还未上传头像')
      // 显示弹框
      this.showCodeDialog = true
      // 数据更新和DOM渲染是异步的，所以要使用nextTick
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 编辑角色
    async  editRole(id) {
      this.userId = id // props传值 是异步的
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }
}
</script>
